package com.gsoe.auth.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gsoe.auth.config.WebSocketServer;
import com.gsoe.auth.mapper.MessageMapper;
import com.gsoe.auth.dto.GetMessageDTO;
import com.gsoe.auth.dto.SendMessageDTO;
import com.gsoe.auth.po.Message;
import com.gsoe.auth.po.UserClass;
import com.gsoe.auth.vo.MessageSocketVO;
import com.gsoe.auth.vo.MessageVO;
import com.gsoe.auth.service.MessageService;
import com.gsoe.auth.service.UserClassService;
import com.gsoe.auth.service.UserInfoService;
import com.gsoe.base.exception.UserException;
import com.gsoe.base.model.User;
import com.gsoe.base.utils.UserUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 班级消息表 服务实现类
 * </p>
 *
 * @author xiaoma
 * @since 2024-12-14
 */
@Service
public class MessageServiceImpl extends ServiceImpl<MessageMapper, Message> implements MessageService {
    @Autowired
    UserInfoService userInfoService;

    @Autowired
    UserClassService userClassService;

    @Autowired
    WebSocketServer webSocketServer;

    @Override
    public void sendMessage(SendMessageDTO sendMessageDTO) {
        if(StringUtils.isEmpty(sendMessageDTO.getMessage()) || sendMessageDTO.getClassId()==null)throw new UserException("sendMessage:必要参数丢失");
        if(countNewLines(sendMessageDTO.getMessage())>=10){
            throw new UserException("行数不能超过10行");
        }
        Message message = new Message();
        BeanUtils.copyProperties(sendMessageDTO, message);
        User loginUser = UserUtil.getLoginUser();
        message.setUserId(loginUser.getId());
        message.setUserName(loginUser.getUserName());
        message.setCreateTime(LocalDateTime.now());
        save(message);

        MessageSocketVO messageSocketVO=MessageSocketVO.builder()
                .id(String.valueOf(message.getId()))
                .avatar(loginUser.getAvatar())
                .classId(String.valueOf(message.getClassId()))
                .message(message.getMessage())
                .userName(loginUser.getUserName())
                .createTime(message.getCreateTime())
                .userId(String.valueOf(loginUser.getId()))
                .build();

        List<Long> userIdList = userClassService.lambdaQuery()
                .select(UserClass::getUserId)
                .eq(UserClass::getClassId, sendMessageDTO.getClassId())
                .list()
                .stream().map(UserClass::getUserId).toList();

        webSocketServer.sendToAllClient(JSON.toJSONString(messageSocketVO),w ->{
            Long id = w.getUser().getId();
            return userIdList.contains(id);
        });
    }

    @Override
    public List<MessageVO> getMessage(GetMessageDTO getMessageDTO) {

        List<Message> messages = lambdaQuery()
                .eq(Message::getClassId, getMessageDTO.getClassId())
                .orderByAsc(Message::getCreateTime)
                .list();

        List<User> list = userInfoService.list();
        Map<Long, String> collect = list.stream().filter(user -> StringUtils.isNotEmpty(user.getAvatar())).collect(Collectors.toMap(User::getId, User::getAvatar));


        return messages.stream().map(message -> {
            MessageVO messageVO = new MessageVO();
            BeanUtils.copyProperties(message, messageVO);
            messageVO.setAvatar(collect.get(message.getUserId()));
            return messageVO;
        }).toList();
    }
    private int countNewLines(String str) {
        int count = 0;
        int index = 0;
        while ((index = str.indexOf('\n', index)) != -1) {
            count++;
            index++;
        }
        return count;
    }
}
